package jsoniterx

import (
	"gitee.com/youbeiwuhuan/taotao-tools4go/base-tools/tagx"
	jsoniter "github.com/json-iterator/go"
	"reflect"
	"time"
	"unsafe"
)

//----- 1. 定义time.Time对应的解码编码器  ------------------------------------------------

type TimeDecoder struct {
	format string
}

func (decoder *TimeDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
	t, err := time.Parse(decoder.format, iter.ReadString())
	if err != nil {
		iter.ReportError("decode time", err.Error())
		return
	}
	*(*time.Time)(ptr) = t
}

func NewTimeDecoder(format string) *TimeDecoder {
	return &TimeDecoder{format}
}

type TimeEncoder struct {
	format string
}

func (encoder *TimeEncoder) IsEmpty(ptr unsafe.Pointer) bool {
	t := *(*time.Time)(ptr)
	return t.IsZero()
}
func (encoder *TimeEncoder) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
	t := *(*time.Time)(ptr)
	stream.WriteString(t.Format(encoder.format))
}

func NewTimeEncoder(format string) *TimeEncoder {
	return &TimeEncoder{format}
}

//----- 2. 定义解码编码器对应的扩展注册逻辑  ------------------------------------------------

type UpdateStructTimeFieldDescriptorExtension struct {
	jsoniter.DummyExtension
}

func (extension *UpdateStructTimeFieldDescriptorExtension) UpdateStructDescriptor(structDescriptor *jsoniter.StructDescriptor) {

	// 获取结构体标签注册解析
	for _, binding := range structDescriptor.Fields {
		format := binding.Field.Tag().Get(tagx.FormatTagName)
		if "" == format {
			continue
		}

		if binding.Field.Type().Type1() != reflect.TypeOf(time.Time{}) {
			continue
		}
		binding.Encoder = NewTimeEncoder(format)
		binding.Decoder = NewTimeDecoder(format)
	}

}
